<template>
  <div class="game-container">
    <button id="game" @click="startGame">{{ gameButtonText }}</button>
    
    <div class="player-controls blue-controls">
      <h3>蓝色玩家</h3>
      <div class="controls-row">
        <div class="key" :class="{ active: keysPressed.has('ArrowLeft') }">←</div>
      </div>
      <div class="controls-row">
        <div class="key" :class="{ active: keysPressed.has('ArrowUp') }">↑</div>
      </div>
      <div class="controls-row">
        <div class="key" :class="{ active: keysPressed.has('ArrowRight') }">→</div>
      </div>
      <div class="controls-row" style="margin-top: 15px;">
        <div class="key" :class="{ active: keysPressed.has('.') }">.</div>
        <div style="line-height: 40px; margin: 0 5px; color: #aaa;">射击</div>
      </div>
    </div>
    
    <div class="player-controls red-controls">
      <h3>红色玩家</h3>
      <div class="controls-row">
        <div class="key" :class="{ active: keysPressed.has('a') }">A</div>
      </div>
      <div class="controls-row">
        <div class="key" :class="{ active: keysPressed.has('w') }">W</div>
      </div>
      <div class="controls-row">
        <div class="key" :class="{ active: keysPressed.has('d') }">D</div>
      </div>
      <div class="controls-row" style="margin-top: 15px;">
        <div class="key" :class="{ active: keysPressed.has('m') }">M</div>
        <div style="line-height: 40px; margin: 0 5px; color: #aaa;">射击</div>
      </div>
    </div>
    
    <div 
      class="player blueplayer" 
      :style="{ right: blueplayer.x + 'px', bottom: blueplayer.y + 'px' }"
    >
      <div class="health">{{ blueplayer.health }}</div>
      <!-- 显示玩家方向 -->
      <div class="direction-indicator" :class="blueplayer.direction"></div>
    </div>
    
    <div 
      class="player redplayer" 
      :style="{ left: redplayer.x + 'px', bottom: redplayer.y + 'px' }"
    >
      <div class="health">{{ redplayer.health }}</div>
      <!-- 显示玩家方向 -->
      <div class="direction-indicator" :class="redplayer.direction"></div>
    </div>
    
    <div 
      v-for="(bullet, index) in bullets" 
      :key="index"
      class="bullet"
      :class="bullet.shooter === 'blue' ? 'blue-bullet' : 'red-bullet'"
      :style="{ left: bullet.x + 'px', bottom: bullet.y + 'px' }"
    ></div>
    
    <div 
      v-if="gameOver" 
      class="game-over-message"
    >
      游戏结束!<br>
      <span>{{ winner }} 胜利!</span>
    </div>
    
    <div class="ground"></div>
    
    <div class="instructions">
      蓝色玩家: 方向键移动，"."键射击 | 红色玩家: WASD移动，"M"键射击
      <p>射击方向取决于移动方向</p>
    </div>
    
    <audio ref="audioPlayer" loop>
      <source src="../assets/music.mp3" type="audio/mpeg">
    </audio>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted, onBeforeUnmount } from 'vue';

const blueplayer = reactive({
  x: 100,
  y: 0,
  health: 3,
  isJumping: false,
  direction: 'left' // 初始方向
});

const redplayer = reactive({
  x: 50,
  y: 0,
  health: 3,
  isJumping: false,
  direction: 'right' // 初始方向
});

const keysPressed = ref(new Set());
const bullets = ref([]);
const gameOver = ref(false);
const winner = ref('');
const isGameStarted = ref(false);
const gameButtonText = ref('开始游戏');
const audioPlayer = ref(null);

const combinations = [
  { keys: ['ArrowLeft', 'ArrowUp'], triggered: false },
  { keys: ['ArrowRight', 'ArrowUp'], triggered: false },
  { keys: ['a', 'w'], triggered: false },
  { keys: ['d', 'w'], triggered: false }
];

let gameInterval;

onBeforeUnmount(() => {
  document.removeEventListener('keydown', handleKeyDown);
  document.removeEventListener('keyup', handleKeyUp);
  clearInterval(gameInterval);
});

onMounted(() => {
  gameInterval = setInterval(gameLoop, 1000 / 60); // 60 FPS
  document.addEventListener('keydown', handleKeyDown);
  document.addEventListener('keyup', handleKeyUp);
});

function checkCombinations() {
  for (const combo of combinations) {
    if (combo.keys.every((key) => keysPressed.value.has(key))) {
      combo.triggered = true;
    } else {
      combo.triggered = false;
    }
  }
}

function handleKeyDown(event) {
  if (!isGameStarted.value) return;
  
  // 防止滚动
  if (['ArrowLeft', 'ArrowUp', 'ArrowRight', 'a', 'w', 'd', '.', 'm'].includes(event.key)) {
    event.preventDefault();
  }
  
  keysPressed.value.add(event.key);
  checkCombinations();
  
  if (event.key === 'a' || event.key === 'd' || event.key === 'w') {
    moveRedPlayer(event);
  } else if (event.key === 'ArrowLeft' || event.key === 'ArrowRight' || event.key === 'ArrowUp') {
    moveBluePlayer(event);
  }
  
  // 射击功能
  if (event.key === '.' && isGameStarted.value) {
    shoot('blue');
  }
  
  if (event.key === 'm' && isGameStarted.value) {
    shoot('red');
  }
}

function handleKeyUp(event) {
  if (!isGameStarted.value) return;
  
  keysPressed.value.delete(event.key);
  checkCombinations();
}

function gameLoop() {
  // 更新子弹位置
  updateBullets();
  
  // 检测子弹碰撞
  checkBulletCollisions();
}

function moveBluePlayer(event) {
  const jumpHeight = 100;
  const moveDistance = 10;
  
  if (keysPressed.value.has('ArrowRight') && keysPressed.value.has('ArrowUp')) {
    blueplayer.isJumping = true;
    blueplayer.direction = 'right'; // 设置方向为右
    initiateJump(blueplayer, jumpHeight, 500, 500, (-3 * Math.PI) / 4);
  } else if (keysPressed.value.has('ArrowLeft') && keysPressed.value.has('ArrowUp')) {
    blueplayer.isJumping = true;
    blueplayer.direction = 'left'; // 设置方向为左
    initiateJump(blueplayer, jumpHeight, 500, 500, -Math.PI / 4);
  } else if (event.key === 'ArrowRight' && !blueplayer.isJumping) {
    blueplayer.x = Math.max(0, blueplayer.x - moveDistance);
    blueplayer.direction = 'right'; // 设置方向为右
  } else if (event.key === 'ArrowLeft' && !blueplayer.isJumping) {
    blueplayer.x = Math.min(1050 - 100, blueplayer.x + moveDistance);
    blueplayer.direction = 'left'; // 设置方向为左
  } else if (event.key === 'ArrowUp' && !blueplayer.isJumping) {
    blueplayer.isJumping = true;
    initiateJump(blueplayer, 71, 500, 500, -Math.PI / 2);
  }
}

function moveRedPlayer(event) {
  const jumpHeight = 100;
  const moveDistance = 10;
  
  if (keysPressed.value.has('d') && keysPressed.value.has('w')) {
    redplayer.isJumping = true;
    redplayer.direction = 'right'; // 设置方向为右
    initiateJump(redplayer, jumpHeight, 500, 500, -Math.PI / 4);
  } else if (keysPressed.value.has('a') && keysPressed.value.has('w')) {
    redplayer.isJumping = true;
    redplayer.direction = 'left'; // 设置方向为左
    initiateJump(redplayer, jumpHeight, 500, 500, (-3 * Math.PI) / 4);
  } else if (event.key === 'a' && !redplayer.isJumping) {
    redplayer.x = Math.max(0, redplayer.x - moveDistance);
    redplayer.direction = 'left'; // 设置方向为左
  } else if (event.key === 'd' && !redplayer.isJumping) {
    redplayer.x = Math.min(1050- 100, redplayer.x + moveDistance);
    redplayer.direction = 'right'; // 设置方向为右
  } else if (event.key === 'w' && !redplayer.isJumping) {
    redplayer.isJumping = true;
    initiateJump(redplayer, 71, 500, 500, -Math.PI / 2);
  }
}

function initiateJump(player, height, jumpDuration, fallDuration, angle) {
  let startTime = null;
  const g = 100;
  const vx = 30 * Math.cos(angle);
  const vy0 = -Math.sqrt(2 * 6 * height) * Math.sin(angle);

  const animate = (timestamp) => {
    if (!startTime) startTime = timestamp;
    const progress = timestamp - startTime;
    const t = progress / 1000;

    const x = player.x + vx * t;
    const y = player.y + vy0 * t + 0.5 * 6 * t * t;

    player.x = x;
    player.y = y;

    if (t < jumpDuration / 1000) {
      requestAnimationFrame(animate);
    } else {
      fall(player, x, y, height, fallDuration, vx, g);
    }
    
    if (player.x <= 0 || player.x >= 1050 - 100 || player.y >= 500) {
      player.x = Math.max(0, Math.min(1050 - 100, player.x));
      player.y = Math.min(500, player.y);
      fall(player, player.x, player.y, height, fallDuration, 0, g);
    }
  }

  requestAnimationFrame(animate);
}

function fall(player, initialX, initialY, height, duration, vx, g) {
  let startTime = null;

  const animate = (timestamp) => {
    if (!startTime) startTime = timestamp;
    const progress = timestamp - startTime;
    const t = progress / 700;

    const x = initialX + 2 * vx * t;
    const y = initialY - 0.5 * g * t * t;

    player.x = x;
    player.y = Math.max(0, y);

    if (y > 0 || t < duration / 1000) {
      requestAnimationFrame(animate);
    } else {
      player.isJumping = false;
    }
  }

  requestAnimationFrame(animate);
}

// 修改后的射击功能 - 根据方向射击
function shoot(shooter) {
  const player = shooter === 'blue' ? blueplayer : redplayer;
  
  // 根据玩家方向确定射击方向
  const direction = player.direction === 'left' ? -1 : 1;
  
  // 根据方向调整子弹发射位置
  const offset = direction === -1 ? -20 : 20;
  
  bullets.value.push({
    x: player.x + offset,
    y: player.y + 20,
    speed: 8 * direction,
    shooter: shooter
  });
}

// 更新子弹位置
function updateBullets() {
  for (let i = bullets.value.length - 1; i >= 0; i--) {
    const bullet = bullets.value[i];
    bullet.x += bullet.speed;
    
    // 移除超出屏幕的子弹
    if (bullet.x < -50 || bullet.x > window.innerWidth + 50) {
      bullets.value.splice(i, 1);
    }
  }
}

// 检测子弹碰撞
function checkBulletCollisions() {
  for (let i = bullets.value.length - 1; i >= 0; i--) {
    const bullet = bullets.value[i];
    
    // 检测蓝色子弹击中红色玩家
    if (bullet.shooter === 'blue') {
      const dx = Math.abs(bullet.x - (redplayer.x + 20));
      const dy = Math.abs(bullet.y - (redplayer.y + 20));
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < 30) {
        redplayer.health--;
        bullets.value.splice(i, 1);
        if (redplayer.health <= 0) endGame('蓝色玩家');
      }
    }
    
    // 检测红色子弹击中蓝色玩家
    if (bullet.shooter === 'red') {
      const dx = Math.abs(bullet.x - (blueplayer.x + 20));
      const dy = Math.abs(bullet.y - (blueplayer.y + 20));
      const distance = Math.sqrt(dx * dx + dy * dy);
      
      if (distance < 30) {
        blueplayer.health--;
        bullets.value.splice(i, 1);
        if (blueplayer.health <= 0) endGame('红色玩家');
      }
    }
  }
}

function startGame() {
  isGameStarted.value = true;
  gameButtonText.value = '再玩一次';
  
  // 重置玩家位置和生命值
  blueplayer.x = 100;
  blueplayer.y = 0;
  blueplayer.health = 3;
  blueplayer.direction = 'left';
  
  redplayer.x = 50;
  redplayer.y = 0;
  redplayer.health = 3;
  redplayer.direction = 'right';
  
  // 清空子弹
  bullets.value = [];
  gameOver.value = false;
  
  // 播放背景音乐
  if (audioPlayer.value) {
    audioPlayer.value.play();
  }
}

function endGame(winningPlayer) {
  gameOver.value = true;
  winner.value = winningPlayer;
  isGameStarted.value = false;
  
  // 暂停背景音乐
  if (audioPlayer.value) {
    audioPlayer.value.pause();
  }
}
</script>

<style scoped>
.game-container {
  position: relative;
  width: 100%;
  max-width: 1000px;
  height: 600px;
  margin: 0 auto;
  background: rgba(0, 0, 0, 0.7);
  border-radius: 15px;
  box-shadow: 0 0 30px rgba(0, 0, 0, 0.8);
  overflow: hidden;
  border: 3px solid #444;
  background-image: 
    radial-gradient(circle at 10% 20%, rgba(255,255,255,0.05) 0%, transparent 2%),
    radial-gradient(circle at 90% 80%, rgba(255,255,255,0.05) 0%, transparent 2%);
  background-size: 30px 30px;
  background-color: #121212;
}

#game {
  position: absolute;
  top: 80%;
  left: 80%;
  transform: translate(-80%, -80%);
  padding: 15px 40px;
  font-size: 24px;
  background: linear-gradient(to bottom, #3498db, #2980b9);
  color: white;
  border: none;
  border-radius: 50px;
  cursor: pointer;
  box-shadow: 0 5px 15px rgba(0,0,0,0.3);
  transition: all 0.3s;
  z-index: 5;
  font-weight: bold;
}

#game:hover {
  transform: translate(-50%, -50%) scale(1.05);
  box-shadow: 0 7px 20px rgba(0,0,0,0.4);
}

#game:active {
  transform: translate(-50%, -50%) scale(0.98);
}

.player-controls {
  position: absolute;
  top: 20px;
  padding: 15px;
  background: rgba(0,0,0,0.6);
  border-radius: 10px;
  border: 1px solid #444;
}

.blue-controls {
  right: 20px;
  border-right: 3px solid #3498db;
}

.red-controls {
  left: 20px;
  border-left: 3px solid #e74c3c;
}

.player-controls h3 {
  margin-bottom: 10px;
  color: #ddd;
}

.controls-row {
  display: flex;
  justify-content: center;
  gap: 5px;
  margin-top: 5px;
}

.key {
  display: inline-block;
  width: 40px;
  height: 40px;
  background: #333;
  color: #ddd;
  border-radius: 5px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  box-shadow: 0 3px 0 #222;
}

.key.active {
  background: #555;
  transform: translateY(2px);
  box-shadow: 0 1px 0 #222;
}

.player {
  position: absolute;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-weight: bold;
  box-shadow: 0 0 10px currentColor;
  transition: transform 0.1s;
}

.player:active {
  transform: scale(0.95);
}

.blueplayer {
  background: radial-gradient(circle at 30% 30%, #3498db, #1a5276);
  color: #d6eaf8;
  right: 0;
  bottom: 0;
}

.redplayer {
  background: radial-gradient(circle at 30% 30%, #e74c3c, #922b21);
  color: #fadbd8;
  left: 0;
  bottom: 0;
}

.health {
  position: absolute;
  top: -25px;
  width: 100%;
  text-align: center;
  font-size: 18px;
  text-shadow: 0 0 5px rgba(0,0,0,0.8);
}

.bullet {
  position: absolute;
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.blue-bullet {
  background: linear-gradient(to right, #3498db, #85c1e9);
  box-shadow: 0 0 5px #3498db;
}

.red-bullet {
  background: linear-gradient(to right, #e74c3c, #f1948a);
  box-shadow: 0 0 5px #e74c3c;
}

.game-over-message {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 48px;
  text-align: center;
  text-shadow: 0 0 10px rgba(0,0,0,0.8);
  z-index: 10;
  background: rgba(0, 0, 0, 0.8);
  padding: 30px 60px;
  border-radius: 15px;
  border: 3px solid gold;
  animation: pulse 1.5s infinite;
}

.game-over-message span {
  color: gold;
  font-size: 56px;
  display: block;
  margin-top: 10px;
}

.ground {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 20px;
  background: linear-gradient(to bottom, #5d4037, #4e342e);
  border-top: 2px solid #8d6e63;
}

.instructions {
  position: absolute;
  bottom: 20px;
  left: 0;
  right: 0;
  text-align: center;
  color: #ddd;
  font-size: 16px;
  padding: 0 20px;
  z-index: 2;
}

/* 方向指示器 */
.direction-indicator {
  position: absolute;
  width: 0;
  height: 0;
  border-top: 5px solid transparent;
  border-bottom: 5px solid transparent;
  bottom: 15px;
}

.direction-indicator.left {
  border-right: 8px solid white;
  left: -12px;
}

.direction-indicator.right {
  border-left: 8px solid white;
  right: -12px;
}

@keyframes pulse {
  0% { box-shadow: 0 0 0 0 rgba(255, 215, 0, 0.4); }
  70% { box-shadow: 0 0 0 15px rgba(255, 215, 0, 0); }
  100% { box-shadow: 0 0 0 0 rgba(255, 215, 0, 0); }
}
</style>